<template>
  <div>
    <div class="image-box" ref="downloadRef">
      <div class="text">恭顺安康</div>
      <img class="picture" src="@/assets/images/study-dog.png" alt="" />
    </div>
    <el-button type="primary" plain @click="download">下载图片</el-button>
  </div>
</template>

<script setup>
import { ref } from "vue";
import html2canvas from "html2canvas";

const downloadRef = ref();

const dataURLtoBlob = (dataurl) => {
  var arr = dataurl.split(","); //分割为数组，分割到第一个逗号
  let bstr = window.atob(arr[1]);
  let n = bstr.length;
  let u8arr = new Uint8Array(n);
  while (n--) {
    u8arr[n] = bstr.charCodeAt(n);
  }
  return new Blob([u8arr], { type: "png" });
};

const download = () => {
  html2canvas(downloadRef.value).then((canvas) => {
    let dataURL = canvas.toDataURL("image/png"); //base64格式的图片 url
    const blobUrl = dataURLtoBlob(dataURL); //转化成blob格式的图片 Blob{size:xx,type:xx}
    var fileUrl = URL.createObjectURL(blobUrl); //URL.createObjectURL()创建一个指向File或Blob对象的URL。这个URL可以被用于指定一个HTML标签的href属性

    // 创建a标签下载图片
    var addElement = document.createElement("a");
    addElement.href = fileUrl;
    addElement.download = "恭顺安康.png";

    document.body.appendChild(addElement);
    addElement.click();
    document.body.removeChild(addElement);
  });
};
</script>

<style lang="less" scoped>
.image-box {
  width: 500px;
  height: 520px;
  border: 1px solid #ccc;
  background-color: aqua;
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column;
  font-weight: 700;
  font-size: 28px;
  margin-bottom: 10px;

  .text {
    color: #fff;
    margin-bottom: 10px;
  }
  .picture {
    width: 400px;
    height: 400px;
  }
}
</style>
